<script setup lang="ts">
import {
  Document,
  Menu as IconMenu,
  Location,
  HomeFilled,
  User,
  Setting,
  ArrowLeftBold,
  ArrowRightBold,
} from '@element-plus/icons-vue'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

type BreakpointDirection = 'narrowing' | 'widening'

interface BreakpointCrossEvent {
  breakpoint: Breakpoint
  direction: BreakpointDirection
  fromWidth: number
  toWidth: number
}

const route = useRoute()
const router = useRouter()

const isCollapse = ref(false)
const showTool = ref(true)

// ===== 配置：断点数组（必须升序！）=====
const BREAKPOINTS = [576, 768, 1024, 1280] as const // 使用 as const 保留字面量类型
type Breakpoint = (typeof BREAKPOINTS)[number] // 推导出 576 | 768 | 1024 | 1280

// ===== 状态 =====
const previousWidth = ref<number>(window.innerWidth)

// ===== 工具：防抖 =====
function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number,
): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout> | null = null
  return (...args: Parameters<T>) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => func(...args), delay)
  }
}

// ===== 检测跨越的断点 =====
function detectCrossedBreakpoints(from: number, to: number): BreakpointCrossEvent[] {
  const events: BreakpointCrossEvent[] = []

  for (const bp of BREAKPOINTS) {
    const wasAbove = from > bp
    const isNowAbove = to > bp

    if (wasAbove && !isNowAbove) {
      // 缩小：从 >bp 到 <= bp
      events.push({
        breakpoint: bp,
        direction: 'narrowing',
        fromWidth: from,
        toWidth: to,
      })
    } else if (!wasAbove && isNowAbove) {
      // 放大：从 <= bp 到 > bp
      events.push({
        breakpoint: bp,
        direction: 'widening',
        fromWidth: from,
        toWidth: to,
      })
    }
  }

  return events
}

// ===== Resize 处理 =====
const handleResize = debounce(() => {
  const currentWidth = window.innerWidth
  const events = detectCrossedBreakpoints(previousWidth.value, currentWidth)

  for (const event of events) {
    console.log(
      event.direction === 'narrowing'
        ? `🎯 缩小经过断点 ${event.breakpoint}px`
        : `🚀 放大经过断点 ${event.breakpoint}px`,
      event,
    )

    // 👇 在这里执行你的业务逻辑
    if (event.direction == 'narrowing') {
      isCollapse.value = true
    }
    if (event.breakpoint == 576) {
      showTool.value = event.direction == 'widening'
    }
  }

  previousWidth.value = currentWidth
}, 150)

// ===== 生命周期 =====
onMounted(() => {
  if (window.innerWidth < 576) {
    isCollapse.value = true
    showTool.value = false
  }
  previousWidth.value = window.innerWidth
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

const changeCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleOpen = (key: string, keyPath: string[]) => {
  isCollapse.value = false
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
</script>

<template>
  <div class="left-nav-wrap" :class="{ collapsed: isCollapse }">
    <!-- 左侧任务栏 -->
    <el-menu
      id="left-nav-menu"
      active-text-color="#e1a43a"
      background-color="#304156"
      text-color="#fff"
      router
      :class="{ collapsed: isCollapse }"
      :default-active="route.path"
      :collapse="isCollapse"
      @open="handleOpen"
      @close="handleClose"
    >
      <div v-if="showTool" class="tool-line">
        <el-button @click="changeCollapse">
          <el-icon>
            <ArrowLeftBold v-if="!isCollapse" />
            <ArrowRightBold v-else />
          </el-icon>
        </el-button>
      </div>

      <el-menu-item index="/manage">
        <el-icon><HomeFilled /></el-icon>
        <span>首页</span>
      </el-menu-item>

      <!-- <el-menu-item index="/manage/user">
        <el-icon><User /></el-icon>
        <span>用户管理</span>
      </el-menu-item> -->
      <el-sub-menu index="1">
        <template #title>
          <el-icon><User /></el-icon>
          <span>用户管理</span>
        </template>
        <el-menu-item index="/manage/user">用户列表</el-menu-item>
        <el-menu-item index="/manage/license-plate">车牌列表</el-menu-item>
      </el-sub-menu>

      <el-menu-item index="/manage/equipment">
        <el-icon><location /></el-icon>
        <span>设备管理</span>
      </el-menu-item>

      <el-menu-item index="/manage/notification">
        <el-icon><document /></el-icon>
        <span>通知中心</span>
      </el-menu-item>

      <el-menu-item index="/manage/record">
        <el-icon><IconMenu /></el-icon>
        <span>记录查询</span>
      </el-menu-item>

      <el-menu-item index="/manage/personal">
        <el-icon><Setting /></el-icon>
        <span>个人中心</span>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<style lang="css"></style>

<style scoped lang="scss">
.left-nav-wrap {
  transition: width 0.3s ease;
  width: var(--left-nav-width);
  min-width: var(--left-nav-width);
  transition: all 0.3s ease-in-out;

  &.collapsed {
    width: 64px; /* Element Plus 默认折叠宽度 */
    min-width: 64px;
  }
}

.el-menu {
  transition: width 0.3s ease;
  // width: var(--left-nav-width);
  height: calc(100vh - var(--header-height));
  position: fixed;
  top: var(--header-height);
  left: 0;

  .el-sub-menu {
    padding-right: 0px;
  }

  li {
    padding-right: 45px;
  }
  // 调整悬停bg颜色
  // --el-menu-hover-bg-color: #006df1 !important;

  &.collapsed {
    // width: 64px; /* Element Plus 默认折叠宽度 */
    padding-right: 0px;
  }
}

.tool-line {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: end;
  align-items: center;

  @media screen and (max-width: 576px) {
    // display: none;
  }

  button {
    height: 100%;
    aspect-ratio: 1/1;
    background-color: #304156;
    border: 0;
  }
}
</style>
